import { createRouter,createWebHashHistory } from "vue-router";
import api from "../api";
import Home from '../components/Home.vue'
import store from "../store";
import storage from "../utils/storage";
// 建立异步路由解析规则
const genearateRoute=(menuList)=>{
    let arr=[]
    const deepList = list => {
        while (list.length) {
            let item=list.pop()
            if (item.action) {
                // 二级菜单
                arr.push({
                    path:item.path,
                    name:item.component,
                    meta:{
                        title:item.menuName
                    },
                },)
            }else if (item.children) {
                deepList(item.children)
            }
        }
    };
    deepList(menuList)
    return arr
}

// 异步路由：动态从后端获取的路由
const routes=[
    {
        path:'/',
        name:'home',
        component:Home,
        meta:{
            title:'首页'
        },
        redirect:'welcome',
        children:[
            {
                path:'welcome',
                name:'welcome',
                component:()=>import('../views/Welcome.vue')
            },
        ],
        beforeEnter:(to,from,next)=>{
            if (!storage.getItem('userInfo')) {
                router.push('/login')
            }else{
                next()
            }
        }
    },
    {
        path:'/login',
        name:'login',
        meta:{
            title:'登录'
        },
        component:()=>import('../views/Login.vue')
    },
    {
        path:'/404',
        name:'404',
        meta:{
            title:'404'
        },
        component:()=>import('../views/404.vue')
    }
]

const router=createRouter({
    history:createWebHashHistory(),
    routes
})

// 异步路由拼接基本思路：新增路由对象
// router.addRoute('home',{
//     path:'/system/user',
//     name:'user',
//     meta:{
//         title:'用户'
//     },
//     component:()=>import('../views/User.vue')
// },)

// 获取异步路由
const asyncLoadRoute=async()=>{
    // let userInfo=store.state.userInfo
    let userInfo=storage.getItem('userInfo')||{}
    if (userInfo.token) {
        // 防止缓存被修改，这里权限列表应请求回来
        let {menuList}=await api.getPermissionList()
        // 路由对象信息
        let asyncRoutes=genearateRoute(menuList)
        // component属于文件引入，不依靠数据请求
        // vite中一个api获取vue文件
        asyncRoutes.map(route=>{
            const modules=import.meta.glob('../views/*.vue')
            let url=`../views/${route.name}.vue`
            route.component=modules[url]
        })
        // 通过循环将每个异步路由对象的信息通过addRoute放入路由规则中
        asyncRoutes.forEach(route=>{
            router.addRoute('home',route)
        })
    }
}

const checkPermission=(path)=>{
    const routes=router.getRoutes()
    let permis=routes.filter(route=>route.path==path).length;
    if (permis) {
        return true
    } else {
        return false
    }

}


router.beforeEach(async(to,from,next)=>{
    if (to.name) {
        // 判断用户访问的是固定路由还是异步路由
        // 固定路由
        document.title=to.meta.title//设置网页标签标题
        next()
    } else {
        // 异步路由
        await asyncLoadRoute()
        let flag=checkPermission(to.path)
        if (flag) {
            document.title=to.meta.title
            next(to)
        }else{
            next('/404')
        }
    }
})

export default router